//
//  YCLPullDownRefreshControl.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/18.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

/// 刷新控件高度
let YCLRefreshControlHeight: CGFloat = 60
//刷新控件的3种状态
enum YCLPullDownRefreshControlStatus:Int {

    case Normal // 箭头朝下, 下拉刷新
    case PullToRefresh // 箭头朝上, 释放刷新
    case Refreshing // 正在刷新
}

class YCLPullDownRefreshControl: UIView {
    
    //下拉刷新数据闭包
    var  pullDownRefreshHandler: (()->())?
    
    //记录当前状态,默认为normal
    var currentStatus:YCLPullDownRefreshControlStatus = YCLPullDownRefreshControlStatus.Normal{
    
        didSet {
            
            switch currentStatus {
            case .Normal:
                
                arrowView.hidden = false
                rotationView.hidden = true
                messageLabel.text = "下拉刷新"
                
                //清空arrowView的transform
                UIView.animateWithDuration(YCLDefautlAnimDuration, animations: { 
                    
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                
            case .PullToRefresh:
                
                arrowView.hidden = false
                rotationView.hidden = true
                
                messageLabel.text = "释放刷新"
                
                UIView.animateWithDuration(YCLDefautlAnimDuration, animations: { 
                    
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                
                arrowView.hidden = true
                rotationView.hidden = false
                
                messageLabel.text = "正在刷新..."
                
                //添加动画
                let animation = CABasicAnimation.init(keyPath: "transform.rotation")
                animation.toValue = M_PI * 2
                animation.duration = 0.5
                animation.repeatCount = MAXFLOAT
               rotationView.layer.addAnimation(animation, forKey: nil)
                
                //让刷新控件显示出来
                UIView.animateWithDuration(YCLDefautlAnimDuration, animations: { 
                    
                    self.superScrollView?.contentInset.top += YCLRefreshControlHeight
                })
                
                //让控制器开始刷新数据，需要设置闭包进行回调
                
                pullDownRefreshHandler!()
            
            }
            
        }
    }
    
    //开始刷新
    func startRefreshing() {
        
        currentStatus = .Refreshing
    }
    
    //结束刷新
    func endRefreshing() {
    
        currentStatus = .Normal
        
        UIView.animateWithDuration(YCLDefautlAnimDuration) { 
            
            //隐藏刷新控件
            UIView.animateWithDuration(YCLDefautlAnimDuration, animations: {
                
                self.superScrollView?.contentInset.top -= YCLRefreshControlHeight
            })
        }
    }
    
    var superScrollView:UIScrollView?
    
    //监听tableView的滚动
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        //判断父控件是否为能滚动的类型
        if let scrollView = newSuperview as? UIScrollView {
        
            self.superScrollView = scrollView
            
            //使用kvo监听滚动
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue:0), context: nil)
        }
    }
    
    //kvo回调
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        YCLPrint("tableView滚动了:\(superScrollView?.contentOffset.y)")
        //用户用手指拖拽的时候normal<->PullToRefresh
        if superScrollView!.dragging {
            
            //通过contentOffset.y判断状态，若前后状态相同则不用判断，只有在状态不同切换时才需要执行状态的切换
            //-124 =  -scrollView.contentInset.top - CZRefreshControlHeight
            if superScrollView?.contentOffset.y > (-superScrollView!.contentInset.top - YCLRefreshControlHeight) && (currentStatus == .PullToRefresh){
//                YCLPrint("切换到normal状态")
                currentStatus = .Normal
            }else if superScrollView?.contentOffset.y < -superScrollView!.contentInset.top - YCLRefreshControlHeight && currentStatus == .Normal{
//                YCLPrint("切换到PullToRefresh状态")
                
                currentStatus = .PullToRefresh
            }
        }else if currentStatus == .PullToRefresh{
        
            //PullToRefresh->Refreshing
            currentStatus = .Refreshing
            YCLPrint("切换到Refreshing状态")
            
        }

    }
    
    //移除监听
    deinit{
    
        removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        //内部决定控件尺寸
        let newFrame = CGRect.init(x: 0, y:  -YCLRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: YCLRefreshControlHeight)
        super.init(frame: newFrame)
        
//        backgroundColor = UIColor.cyanColor()
        //设置UI
        prepareUI()
    }
    
    private func prepareUI() {
    
        //添加子控件
        addSubview(arrowView)
        addSubview(rotationView)
        addSubview(messageLabel)
        
        //开始时隐藏转轮
        rotationView.hidden = true
        
        //设置约束
        arrowView.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        rotationView.snp_makeConstraints { (make) in
            
            make.center.equalTo(arrowView)
        }
        
        messageLabel.snp_makeConstraints { (make) in
            
            make.centerY.equalTo(self)
            make.leading.equalTo(arrowView.snp_trailing).offset(10)
        }
    }
    
    //MARK 懒加载控件
    
    //箭头
    private lazy var arrowView:UIImageView = UIImageView.init(image: UIImage.init(named: "tableview_pull_refresh"))
    
    //风火轮
    private lazy var rotationView:UIImageView = UIImageView.init(image: UIImage.init(named: "tableview_loading"))
    
    //文字
    private lazy var messageLabel:UILabel = {
    
        let label = UILabel()
        
        label.text = "下拉刷新"
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        label.sizeToFit()
        
        return label
    }()
    
    
}
